# -*- coding: utf-8 -*-
"""
心理咨询师服务系统 - 测评API
"""

from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.api.assessments import bp
from app.models import Assessment, AssessmentAnswer, AssessmentScore, Scale, ScaleQuestion, QuestionOption, ScaleScoringRule
from app import db
from app.utils.helpers import success_response, error_response
from datetime import datetime
import json


@bp.route('/<int:assessment_id>', methods=['GET'])
@jwt_required()
def get_assessment(assessment_id):
    """获取测评详情"""
    try:
        user_id = get_jwt_identity()
        assessment = Assessment.query.get(assessment_id)
        
        if not assessment:
            return error_response('测评不存在', 404)
        
        # 检查权限
        if assessment.user_id != user_id:
            return error_response('无权访问此测评', 403)
        
        assessment_data = {
            'id': assessment.id,
            'scale_id': assessment.scale_id,
            'scale_title': assessment.scale.title if assessment.scale else None,
            'status': assessment.status_value,  # 使用 status_value 属性
            'current_question': assessment.current_question,
            'total_questions': assessment.total_questions,
            'progress_percentage': assessment.progress_percentage,
            'started_at': assessment.started_at.isoformat() if assessment.started_at else None,
            'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
            'time_spent': assessment.time_spent,
            'estimated_time': assessment.estimated_time
        }
        
        return success_response('获取测评详情成功', assessment_data)
        
    except Exception as e:
        current_app.logger.error(f'获取测评详情失败: {str(e)}')
        return error_response('获取测评详情失败')


@bp.route('/<int:assessment_id>/questions/<int:question_number>', methods=['GET'])
@jwt_required()
def get_assessment_question(assessment_id, question_number):
    """获取测评题目"""
    try:
        user_id = get_jwt_identity()
        assessment = Assessment.query.get(assessment_id)
        
        if not assessment:
            return error_response('测评不存在', 404)
        
        # 检查权限
        if assessment.user_id != user_id:
            return error_response('无权访问此测评', 403)
        
        # 检查测评状态
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.IN_PROGRESS:
            return error_response('测评已结束', 400)
        
        # 获取题目
        question = ScaleQuestion.query.filter_by(
            scale_id=assessment.scale_id,
            question_number=question_number
        ).first()
        
        if not question:
            return error_response('题目不存在', 404)
        
        # 获取选项
        options = QuestionOption.query.filter_by(
            question_id=question.id
        ).order_by(QuestionOption.sort_order).all()
        
        # 获取已有答案
        existing_answer = AssessmentAnswer.query.filter_by(
            assessment_id=assessment_id,
            question_id=question.id
        ).first()
        
        question_data = {
            'id': question.id,
            'question_number': question.question_number,
            'question_text': question.question_text,
            'question_type': question.question_type,
            'is_required': question.is_required,
            'dimension': getattr(question, 'dimension', None),
            'instruction': getattr(question, 'instruction', None),
            'image_url': getattr(question, 'image_url', None),
            'options': [{
                'id': option.id,
                'option_number': option.sort_order,
                'option_text': option.option_text,
                'option_value': option.option_value,
                'image_url': getattr(option, 'image_url', None)
            } for option in options],
            'existing_answer': {
                'selected_options': existing_answer.selected_options if existing_answer else None,
                'answer_text': existing_answer.answer_text if existing_answer else None
            } if existing_answer else None,
            'navigation': {
                'is_first': question_number == 1,
                'is_last': question_number == assessment.total_questions,
                'can_go_back': question_number > 1,
                'can_go_next': question_number < assessment.total_questions
            }
        }
        
        # 更新进度
        progress_data = {
            'current_question': question_number,
            'total_questions': assessment.total_questions,
            'percentage': round((question_number / assessment.total_questions) * 100, 1)
        }
        
        return success_response('获取题目成功', {
            'question': question_data,
            'progress': progress_data,
            'assessment': {
                'id': assessment.id,
                'scale_title': assessment.scale.title if assessment.scale else None,
                'time_spent': assessment.time_spent
            }
        })
        
    except Exception as e:
        current_app.logger.error(f'获取测评题目失败: {str(e)}')
        return error_response('获取题目失败')


@bp.route('/<int:assessment_id>/answers', methods=['POST'])
@jwt_required()
def submit_answer(assessment_id):
    """提交测评答案"""
    try:
        user_id = get_jwt_identity()
        assessment = Assessment.query.get(assessment_id)
        
        if not assessment:
            return error_response('测评不存在', 404)
        
        # 检查权限
        if assessment.user_id != user_id:
            return error_response('无权访问此测评', 403)
        
        # 检查测评状态
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.IN_PROGRESS:
            return error_response('测评已结束', 400)
        
        data = request.get_json()
        question_id = data.get('question_id')
        selected_options = data.get('selected_options')
        answer_text = data.get('answer_text')
        time_spent = data.get('time_spent', 0)
        
        if not question_id:
            return error_response('请提供题目ID')
        
        # 获取题目
        question = ScaleQuestion.query.get(question_id)
        if not question or question.scale_id != assessment.scale_id:
            return error_response('题目不存在', 404)
        
        # 检查是否已有答案
        existing_answer = AssessmentAnswer.query.filter_by(
            assessment_id=assessment_id,
            question_id=question_id
        ).first()
        
        if existing_answer:
            # 更新现有答案
            existing_answer.selected_options = selected_options
            existing_answer.answer_text = answer_text
            existing_answer.time_spent = time_spent
            existing_answer.answered_at = datetime.utcnow()
            answer = existing_answer
        else:
            # 创建新答案
            answer = AssessmentAnswer(
                assessment_id=assessment_id,
                question_id=question_id,
                question_number=question.question_number,
                selected_options=selected_options,
                answer_text=answer_text,
                time_spent=time_spent,
                answered_at=datetime.utcnow()
            )
            db.session.add(answer)
        
        # 计算分数
        answer.calculate_score()
        
        # 更新测评进度
        assessment.calculate_progress()
        assessment.update_time_spent()
        
        db.session.commit()
        
        # 获取下一题信息
        next_question_number = question.question_number + 1
        next_question = None
        if next_question_number <= assessment.total_questions:
            next_question = ScaleQuestion.query.filter_by(
                scale_id=assessment.scale_id,
                question_number=next_question_number
            ).first()
        
        result = {
            'answer_id': answer.id,
            'progress_percentage': assessment.progress_percentage,
            'next_question_number': next_question_number if next_question else None,
            'is_last_question': next_question_number > assessment.total_questions
        }
        
        return success_response('提交答案成功', result)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'提交测评答案失败: {str(e)}')
        return error_response('提交答案失败')


@bp.route('/<int:assessment_id>/complete', methods=['POST'])
@jwt_required()
def complete_assessment(assessment_id):
    """完成测评"""
    try:
        user_id = get_jwt_identity()
        assessment = Assessment.query.get(assessment_id)
        
        if not assessment:
            return error_response('测评不存在', 404)
        
        # 检查权限
        if assessment.user_id != user_id:
            return error_response('无权访问此测评', 403)
        
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.IN_PROGRESS:
            return error_response('测评已结束', 400)
        
        # 标记为完成
        assessment.status = AssessmentStatus.COMPLETED
        assessment.completed_at = datetime.utcnow()
        assessment.progress_percentage = 100.0
        
        # 计算最终得分
        calculate_final_scores(assessment)
        
        db.session.commit()
        
        return success_response('测评完成', {'assessment_id': assessment_id})
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'完成测评失败: {str(e)}')
        return error_response('完成测评失败')


@bp.route('/<int:assessment_id>/results', methods=['GET'])
@jwt_required()
def get_assessment_results(assessment_id):
    """获取测评结果"""
    try:
        user_id = get_jwt_identity()
        assessment = Assessment.query.get(assessment_id)
        
        if not assessment:
            return error_response('测评不存在', 404)
        
        # 检查权限
        if assessment.user_id != user_id:
            return error_response('无权访问此测评', 403)
        
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.COMPLETED:
            return error_response('测评尚未完成', 400)
        
        # 获取得分
        scores = AssessmentScore.query.filter_by(assessment_id=assessment_id).all()
        
        score_list = []
        for score in scores:
            score_data = {
                'dimension_name': score.dimension_name,
                'raw_score': score.raw_score,
                'standard_score': score.standard_score,
                'percentile': score.percentile,
                'score_level': score.score_level,
                'interpretation': score.interpretation,
                'suggestions': score.suggestions,
                'min_possible_score': score.min_possible_score,
                'max_possible_score': score.max_possible_score,
                'score_percentage': score.score_percentage
            }
            score_list.append(score_data)
        
        result_data = {
            'assessment': {
                'id': assessment.id,
                'scale_id': assessment.scale_id,
                'scale_title': assessment.scale.title if assessment.scale else None,
                'scale_description': assessment.scale.description if assessment.scale else None,
                'status': assessment.status_value,  # 使用 status_value 属性
                'started_at': assessment.started_at.isoformat() if assessment.started_at else None,
                'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
                'time_spent': assessment.time_spent,
                'progress_percentage': assessment.progress_percentage
            },
            'scores': score_list,
            'completion_date': datetime.utcnow().strftime('%Y年%m月%d日'),
            'assessment_summary': {
                'total_questions': assessment.total_questions,
                'time_spent_minutes': round((assessment.time_spent or 0) / 60, 1),
                'completion_rate': assessment.progress_percentage or 0
            }
        }
        
        return success_response('获取测评结果成功', result_data)
        
    except Exception as e:
        current_app.logger.error(f'获取测评结果失败: {str(e)}')
        return error_response('获取结果失败')


@bp.route('/<int:assessment_id>/abandon', methods=['POST'])
@jwt_required()
def abandon_assessment(assessment_id):
    """放弃测评"""
    try:
        user_id = get_jwt_identity()
        assessment = Assessment.query.get(assessment_id)
        
        if not assessment:
            return error_response('测评不存在', 404)
        
        # 检查权限
        if assessment.user_id != user_id:
            return error_response('无权访问此测评', 403)
        
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.IN_PROGRESS:
            return error_response('测评已结束', 400)
        
        # 标记为放弃
        assessment.status = AssessmentStatus.ABANDONED
        assessment.update_time_spent()
        
        db.session.commit()
        
        return success_response('放弃测评成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'放弃测评失败: {str(e)}')
        return error_response('放弃测评失败')


def calculate_final_scores(assessment):
    """计算测评最终得分"""
    try:
        # 获取量表的计分规则
        scoring_rules = ScaleScoringRule.query.filter_by(scale_id=assessment.scale_id).all()
        
        for rule in scoring_rules:
            # 计算维度得分
            score = calculate_dimension_score(assessment, rule.dimension)
            
            if score is not None:
                # 创建或更新得分记录
                assessment_score = AssessmentScore.query.filter_by(
                    assessment_id=assessment.id,
                    dimension_name=rule.dimension
                ).first()
                
                if not assessment_score:
                    assessment_score = AssessmentScore(
                        assessment_id=assessment.id,
                        dimension_name=rule.dimension,
                        scale_id=assessment.scale_id
                    )
                    db.session.add(assessment_score)
                
                # 更新得分
                assessment_score.raw_score = score
                assessment_score.min_possible_score = rule.min_score
                assessment_score.max_possible_score = rule.max_score
                
                # 计算标准分和百分位
                if rule.max_score > rule.min_score:
                    assessment_score.score_percentage = (score - rule.min_score) / (rule.max_score - rule.min_score) * 100
                    assessment_score.standard_score = assessment_score.score_percentage
                    assessment_score.percentile = assessment_score.score_percentage
                
                # 生成解释
                assessment_score.interpretation = generate_interpretation(rule, score)
                assessment_score.score_level = determine_score_level(rule, score)
        
        db.session.commit()
        
    except Exception as e:
        current_app.logger.error(f'计算最终得分失败: {str(e)}')


def calculate_dimension_score(assessment, dimension=None):
    """计算维度得分"""
    try:
        # 获取该维度的所有答案
        query = AssessmentAnswer.query.join(ScaleQuestion).filter(
            AssessmentAnswer.assessment_id == assessment.id
        )
        
        if dimension:
            query = query.filter(ScaleQuestion.dimension == dimension)
        
        answers = query.all()
        
        total_score = 0
        for answer in answers:
            if answer.option_score is not None:
                total_score += answer.option_score
        
        return total_score
        
    except Exception as e:
        current_app.logger.error(f'计算维度得分失败: {str(e)}')
        return None


def generate_interpretation(rule, score, dimension=None):
    """生成得分解释"""
    if not rule.score_ranges:
        return '暂无解释'
    
    # 根据得分范围找到对应的解释
    for score_range in rule.score_ranges:
        if score_range['min_score'] <= score <= score_range['max_score']:
            return score_range.get('interpretation', '暂无解释')
    
    return '得分超出正常范围'


def determine_score_level(rule, score):
    """确定得分等级"""
    if not rule.score_ranges:
        return 'normal'
    
    # 根据得分范围确定等级
    for score_range in rule.score_ranges:
        if score_range['min_score'] <= score <= score_range['max_score']:
            return score_range.get('level', 'normal')
    
    return 'abnormal'


# ====== 匿名评测API ======

@bp.route('/anonymous', methods=['POST'])
def start_anonymous_assessment():
    """开始匿名测评"""
    try:
        data = request.get_json()
        scale_id = data.get('scale_id')
        basic_info = data.get('basic_info', {})
        
        if not scale_id:
            return error_response('请提供量表ID')
        
        # 获取量表信息
        scale = Scale.query.get(scale_id)
        if not scale:
            return error_response('量表不存在', 404)
        
        # 修复：直接比较枚举值，不使用.value
        if scale.status != 'PUBLISHED' or not scale.is_public:
            return error_response('量表不可访问', 403)
        
        # 生成会话ID
        import uuid
        session_id = str(uuid.uuid4())
        
        # 创建匿名评测记录
        from app.models.assessment import AssessmentStatus
        assessment = Assessment(
            user_id=None,  # 匿名用户
            scale_id=scale_id,
            status=AssessmentStatus.IN_PROGRESS,
            total_questions=scale.question_count,
            estimated_time=scale.estimated_time * 60 if scale.estimated_time else None,
            started_at=datetime.utcnow(),
            is_anonymous=True,
            ip_address=request.remote_addr,
            user_agent=request.headers.get('User-Agent')
        )
        
        db.session.add(assessment)
        db.session.flush()
        
        # 保存基础信息
        if basic_info:
            from app.models import UserBasicInfo
            for field_name, field_value in basic_info.items():
                if field_value:  # 只保存有值的字段
                    basic_info_record = UserBasicInfo(
                        user_id=None,
                        session_id=session_id,
                        assessment_id=assessment.id,
                        field_name=field_name,
                        field_value=str(field_value)
                    )
                    db.session.add(basic_info_record)
        
        # 更新量表使用次数
        scale.usage_count = (scale.usage_count or 0) + 1
        
        db.session.commit()
        
        # 获取第一个题目
        first_question = ScaleQuestion.query.filter_by(
            scale_id=scale_id,
            question_number=1
        ).first()
        
        question_data = None
        if first_question:
            options = QuestionOption.query.filter_by(
                question_id=first_question.id
            ).order_by(QuestionOption.sort_order).all()
            
            question_data = {
                'id': first_question.id,
                'question_number': first_question.question_number,
                'question_text': first_question.question_text,
                'question_type': first_question.question_type,
                'is_required': first_question.is_required,
                'instruction': getattr(first_question, 'instruction', None),
                'image_url': getattr(first_question, 'image_url', None),
                'options': [{
                    'id': option.id,
                    'option_number': option.sort_order,
                    'option_text': option.option_text,
                    'option_value': option.option_value,
                    'image_url': getattr(option, 'image_url', None)
                } for option in options]
            }
        
        result_data = {
            'assessment_id': assessment.id,
            'session_id': session_id,
            'scale': {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time
            },
            'progress': {
                'current_question': 1,
                'total_questions': assessment.total_questions,
                'percentage': 0.0
            },
            'current_question': question_data
        }
        
        return success_response('开始匿名测评成功', result_data)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'开始匿名测评失败: {str(e)}')
        return error_response('开始匿名测评失败')


@bp.route('/anonymous/<int:assessment_id>/question/<int:question_number>', methods=['GET'])
def get_anonymous_question(assessment_id, question_number):
    """获取匿名测评题目"""
    try:
        # 验证评测记录
        assessment = Assessment.query.get(assessment_id)
        if not assessment:
            return error_response('测评不存在', 404)
        
        if not assessment.is_anonymous:
            return error_response('非匿名测评', 403)
        
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.IN_PROGRESS:
            return error_response('测评已结束', 400)
        
        # 获取题目
        question = ScaleQuestion.query.filter_by(
            scale_id=assessment.scale_id,
            question_number=question_number
        ).first()
        
        if not question:
            return error_response('题目不存在', 404)
        
        # 获取选项
        options = QuestionOption.query.filter_by(
            question_id=question.id
        ).order_by(QuestionOption.sort_order).all()
        
        # 获取已有答案
        existing_answer = AssessmentAnswer.query.filter_by(
            assessment_id=assessment_id,
            question_id=question.id
        ).first()
        
        question_data = {
            'id': question.id,
            'question_number': question.question_number,
            'question_text': question.question_text,
            'question_type': question.question_type,
            'is_required': question.is_required,
            'dimension': getattr(question, 'dimension', None),
            'instruction': getattr(question, 'instruction', None),
            'image_url': getattr(question, 'image_url', None),
            'options': [{
                'id': option.id,
                'option_number': option.sort_order,
                'option_text': option.option_text,
                'option_value': option.option_value,
                'image_url': getattr(option, 'image_url', None)
            } for option in options],
            'existing_answer': {
                'selected_options': existing_answer.selected_options if existing_answer else None,
                'answer_text': existing_answer.answer_text if existing_answer else None
            } if existing_answer else None,
            'navigation': {
                'is_first': question_number == 1,
                'is_last': question_number == assessment.total_questions,
                'can_go_back': question_number > 1,
                'can_go_next': question_number < assessment.total_questions
            }
        }
        
        # 更新进度
        progress_data = {
            'current_question': question_number,
            'total_questions': assessment.total_questions,
            'percentage': round((question_number / assessment.total_questions) * 100, 1)
        }
        
        return success_response('获取题目成功', {
            'question': question_data,
            'progress': progress_data,
            'assessment': {
                'id': assessment.id,
                'scale_title': assessment.scale.title if assessment.scale else None,
                'time_spent': assessment.time_spent
            }
        })
        
    except Exception as e:
        current_app.logger.error(f'获取匿名测评题目失败: {str(e)}')
        return error_response('获取题目失败')


@bp.route('/anonymous/<int:assessment_id>/answer', methods=['POST'])
def submit_anonymous_answer(assessment_id):
    """提交匿名测评答案"""
    try:
        # 验证评测记录
        assessment = Assessment.query.get(assessment_id)
        if not assessment:
            return error_response('测评不存在', 404)
        
        if not assessment.is_anonymous:
            return error_response('非匿名测评', 403)
        
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.IN_PROGRESS:
            return error_response('测评已结束', 400)
        
        data = request.get_json()
        question_id = data.get('question_id')
        selected_options = data.get('selected_options')
        answer_text = data.get('answer_text')
        time_spent = data.get('time_spent', 0)
        
        if not question_id:
            return error_response('请提供题目ID')
        
        # 获取题目
        question = ScaleQuestion.query.get(question_id)
        if not question or question.scale_id != assessment.scale_id:
            return error_response('题目不存在', 404)
        
        # 检查是否已有答案
        existing_answer = AssessmentAnswer.query.filter_by(
            assessment_id=assessment_id,
            question_id=question_id
        ).first()
        
        if existing_answer:
            # 更新现有答案
            existing_answer.selected_options = selected_options
            existing_answer.answer_text = answer_text
            existing_answer.time_spent = time_spent
            existing_answer.answered_at = datetime.utcnow()
            answer = existing_answer
        else:
            # 创建新答案
            answer = AssessmentAnswer(
                assessment_id=assessment_id,
                question_id=question_id,
                question_number=question.question_number,
                selected_options=selected_options,
                answer_text=answer_text,
                time_spent=time_spent,
                answered_at=datetime.utcnow()
            )
            db.session.add(answer)
        
        # 计算分数
        answer.calculate_score()
        
        # 更新测评进度
        assessment.calculate_progress()
        assessment.update_time_spent()
        
        # 检查是否完成所有题目
        answered_count = AssessmentAnswer.query.filter_by(assessment_id=assessment_id).count()
        is_completed = answered_count >= assessment.total_questions
        
        if is_completed:
            assessment.status = AssessmentStatus.COMPLETED
            assessment.completed_at = datetime.utcnow()
            
            # 计算最终得分
            calculate_final_scores(assessment)
        
        db.session.commit()
        
        # 准备下一题信息
        next_question_data = None
        if not is_completed and question.question_number < assessment.total_questions:
            next_question_number = question.question_number + 1
            next_question = ScaleQuestion.query.filter_by(
                scale_id=assessment.scale_id,
                question_number=next_question_number
            ).first()
            
            if next_question:
                next_options = QuestionOption.query.filter_by(
                    question_id=next_question.id
                ).order_by(QuestionOption.sort_order).all()
                
                next_question_data = {
                    'id': next_question.id,
                    'question_number': next_question.question_number,
                    'question_text': next_question.question_text,
                    'question_type': next_question.question_type,
                    'is_required': next_question.is_required,
                    'instruction': getattr(next_question, 'instruction', None),
                    'image_url': getattr(next_question, 'image_url', None),
                    'options': [{
                        'id': option.id,
                        'option_number': option.sort_order,
                        'option_text': option.option_text,
                        'option_value': option.option_value,
                        'image_url': getattr(option, 'image_url', None)
                    } for option in next_options]
                }
        
        result = {
            'answer_id': answer.id,
            'progress_percentage': assessment.progress_percentage,
            'is_completed': is_completed,
            'next_question': next_question_data
        }
        
        return success_response('提交答案成功', result)
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'提交匿名测评答案失败: {str(e)}')
        return error_response('提交答案失败')


@bp.route('/anonymous/<int:assessment_id>/results', methods=['GET'])
def get_anonymous_results(assessment_id):
    """获取匿名测评结果"""
    try:
        # 验证评测记录
        assessment = Assessment.query.get(assessment_id)
        if not assessment:
            return error_response('测评不存在', 404)
        
        if not assessment.is_anonymous:
            return error_response('非匿名测评', 403)
        
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.COMPLETED:
            return error_response('测评尚未完成', 400)
        
        # 获取得分
        scores = AssessmentScore.query.filter_by(assessment_id=assessment_id).all()
        
        score_list = []
        for score in scores:
            score_data = {
                'dimension_name': score.dimension_name,
                'raw_score': score.raw_score,
                'standard_score': score.standard_score,
                'percentile': score.percentile,
                'score_level': score.score_level,
                'interpretation': score.interpretation,
                'suggestions': score.suggestions,
                'min_possible_score': score.min_possible_score,
                'max_possible_score': score.max_possible_score,
                'score_percentage': score.score_percentage
            }
            score_list.append(score_data)
        
        # 获取基础信息
        from app.models import UserBasicInfo
        basic_info_records = UserBasicInfo.query.filter_by(assessment_id=assessment_id).all()
        basic_info = {record.field_name: record.field_value for record in basic_info_records}
        
        result_data = {
            'assessment': {
                'id': assessment.id,
                'scale_id': assessment.scale_id,
                'scale_title': assessment.scale.title if assessment.scale else None,
                'scale_description': assessment.scale.description if assessment.scale else None,
                'status': assessment.status_value,  # 使用 status_value 属性
                'started_at': assessment.started_at.isoformat() if assessment.started_at else None,
                'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
                'time_spent': assessment.time_spent,
                'progress_percentage': assessment.progress_percentage
            },
            'basic_info': basic_info,
            'scores': score_list,
            'completion_date': datetime.utcnow().strftime('%Y年%m月%d日'),
            'assessment_summary': {
                'total_questions': assessment.total_questions,
                'time_spent_minutes': round((assessment.time_spent or 0) / 60, 1),
                'completion_rate': 100.0
            }
        }
        
        return success_response('获取匿名测评结果成功', result_data)
        
    except Exception as e:
        current_app.logger.error(f'获取匿名测评结果失败: {str(e)}')
        return error_response('获取结果失败')


@bp.route('/anonymous/<int:assessment_id>/abandon', methods=['POST'])
def abandon_anonymous_assessment(assessment_id):
    """放弃匿名测评"""
    try:
        # 验证评测记录
        assessment = Assessment.query.get(assessment_id)
        if not assessment:
            return error_response('测评不存在', 404)
        
        if not assessment.is_anonymous:
            return error_response('非匿名测评', 403)
        
        from app.models.assessment import AssessmentStatus
        if assessment.status != AssessmentStatus.IN_PROGRESS:
            return error_response('测评已结束', 400)
        
        # 标记为放弃
        assessment.status = AssessmentStatus.ABANDONED
        assessment.update_time_spent()
        
        db.session.commit()
        
        return success_response('放弃测评成功')
        
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f'放弃匿名测评失败: {str(e)}')
        return error_response('放弃测评失败')


@bp.route('/my', methods=['GET'])
@jwt_required()
def get_my_assessments():
    """获取我的测评记录"""
    try:
        user_id = get_jwt_identity()
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        scale_id = request.args.get('scale_id', type=int)
        status = request.args.get('status')
        
        # 构建查询
        query = Assessment.query.filter_by(user_id=user_id)
        
        # 按量表筛选
        if scale_id:
            query = query.filter_by(scale_id=scale_id)
        
        # 按状态筛选
        if status:
            from app.models.assessment import AssessmentStatus
            try:
                query = query.filter_by(status=AssessmentStatus(status))
            except ValueError:
                return error_response('状态参数不正确')
        
        # 分页查询
        pagination = query.order_by(Assessment.created_at.desc()).paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        assessments = []
        for assessment in pagination.items:
            # 计算用时
            duration = None
            if assessment.completed_at and assessment.started_at:
                duration_seconds = (assessment.completed_at - assessment.started_at).total_seconds()
                duration_minutes = int(duration_seconds // 60)
                duration_seconds = int(duration_seconds % 60)
                duration = f"{duration_minutes}分{duration_seconds}秒"
            
            # 计算总分数
            total_score = None
            if assessment.scores:
                total_score = sum(score.raw_score for score in assessment.scores if score.raw_score)
            
            assessment_data = {
                'id': assessment.id,
                'scale_id': assessment.scale_id,
                'scale_title': assessment.scale.title if assessment.scale else None,
                'status': assessment.status_value,
                'progress': assessment.progress_percentage,
                'total_score': total_score,
                'created_at': assessment.created_at.isoformat() if assessment.created_at else None,
                'started_at': assessment.started_at.isoformat() if assessment.started_at else None,
                'completed_at': assessment.completed_at.isoformat() if assessment.completed_at else None,
                'duration': duration,
                'time_spent': assessment.time_spent
            }
            assessments.append(assessment_data)
        
        # 统计信息
        stats = {}
        if scale_id:
            from sqlalchemy import func
            
            # 总测评次数
            total_count = Assessment.query.filter_by(
                user_id=user_id, 
                scale_id=scale_id
            ).count()
            
            # 完成次数
            from app.models.assessment import AssessmentStatus
            completed_count = Assessment.query.filter_by(
                user_id=user_id, 
                scale_id=scale_id,
                status=AssessmentStatus.COMPLETED
            ).count()
            
            # 平均分数 - 通过AssessmentScore计算
            from app.models.assessment import AssessmentScore
            avg_score_result = db.session.query(func.avg(AssessmentScore.raw_score)).join(
                Assessment, AssessmentScore.assessment_id == Assessment.id
            ).filter(
                Assessment.user_id == user_id,
                Assessment.scale_id == scale_id,
                Assessment.status == AssessmentStatus.COMPLETED,
                AssessmentScore.raw_score.isnot(None)
            ).scalar()
            average_score = float(avg_score_result) if avg_score_result else None
            
            # 最近测评日期
            last_assessment = Assessment.query.filter_by(
                user_id=user_id,
                scale_id=scale_id
            ).order_by(Assessment.created_at.desc()).first()
            last_assessment_date = last_assessment.created_at.date() if last_assessment else None
            
            stats = {
                'total_count': total_count,
                'completed_count': completed_count,
                'average_score': average_score,
                'last_assessment_date': last_assessment_date.isoformat() if last_assessment_date else None
            }
            
            # 趋势数据（最近10次完成的测评）
            trend_assessments = Assessment.query.filter(
                Assessment.user_id == user_id,
                Assessment.scale_id == scale_id,
                Assessment.status == AssessmentStatus.COMPLETED
            ).order_by(Assessment.completed_at.desc()).limit(10).all()
            
            trend_data = {
                'labels': [],
                'scores': []
            }
            
            for i, assessment in enumerate(reversed(trend_assessments)):
                # 计算该测评的总分数
                assessment_total_score = 0
                if assessment.scores:
                    assessment_total_score = sum(score.raw_score for score in assessment.scores if score.raw_score)
                
                trend_data['labels'].append(f"第{len(trend_assessments)-i}次")
                trend_data['scores'].append(assessment_total_score)
        else:
            # 当没有指定scale_id时，初始化空的统计数据
            stats = {}
            trend_data = None
        
        result = {
            'assessments': assessments,
            'pagination': {
                'page': pagination.page,
                'pages': pagination.pages,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'has_prev': pagination.has_prev,
                'has_next': pagination.has_next
            },
            'total_pages': pagination.pages,
            'stats': stats,
            'trend_data': trend_data if scale_id else None
        }
        
        return success_response('获取测评记录成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取测评记录失败: {str(e)}')
        return error_response('获取测评记录失败')


@bp.route('/scales', methods=['GET'])
@jwt_required()
def get_my_assessment_scales():
    """获取我参与过测评的量表列表"""
    try:
        user_id = get_jwt_identity()
        
        # 查询用户参与过测评的量表
        from sqlalchemy import func, distinct
        
        # 获取用户测评过的量表ID列表
        scale_ids_query = db.session.query(distinct(Assessment.scale_id)).filter(
            Assessment.user_id == user_id
        ).subquery()
        
        # 获取量表详情
        scales = Scale.query.filter(
            Scale.id.in_(scale_ids_query)
        ).all()
        
        scale_list = []
        for scale in scales:
            # 获取该量表的测评统计
            total_assessments = Assessment.query.filter_by(
                user_id=user_id,
                scale_id=scale.id
            ).count()
            
            from app.models.assessment import AssessmentStatus
            completed_assessments = Assessment.query.filter_by(
                user_id=user_id,
                scale_id=scale.id,
                status=AssessmentStatus.COMPLETED
            ).count()
            
            # 最近一次测评
            last_assessment = Assessment.query.filter_by(
                user_id=user_id,
                scale_id=scale.id
            ).order_by(Assessment.created_at.desc()).first()
            
            scale_data = {
                'id': scale.id,
                'title': scale.title,
                'subtitle': scale.subtitle,
                'description': scale.description,
                'category_name': scale.category.name if scale.category else None,
                'question_count': scale.question_count,
                'estimated_time': scale.estimated_time,
                'usage_count': total_assessments,  # 用户对该量表的使用次数
                'completed_count': completed_assessments,  # 完成次数
                'status': 'PUBLISHED',  # 用户能参与测评的量表都是已发布的
                'last_assessment_date': last_assessment.created_at.isoformat() if last_assessment else None
            }
            scale_list.append(scale_data)
        
        # 按最近测评时间排序
        scale_list.sort(key=lambda x: x['last_assessment_date'] or '', reverse=True)
        
        result = {
            'scales': scale_list,
            'total': len(scale_list)
        }
        
        return success_response('获取量表列表成功', result)
        
    except Exception as e:
        current_app.logger.error(f'获取量表列表失败: {str(e)}')
        return error_response('获取量表列表失败')